/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.x.component.framework;

import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityOptions;
import android.app.AppGlobals;
import android.app.WindowConfiguration.ActivityType;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.os.Looper;
import android.os.RemoteException;
import android.os.UserHandle;
import android.util.Log;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

public class ActivityManagerWrapper {

	private static final String TAG = "ActivityManagerWrapper";

	private static final ActivityManagerWrapper sInstance = new ActivityManagerWrapper();

	// Should match the values in PhoneWindowManager
	public static final String CLOSE_SYSTEM_WINDOWS_REASON_RECENTS = "recentapps";

	private final PackageManager mPackageManager;
	private final BackgroundExecutor mBackgroundExecutor;
	private final TaskStackChangeListeners mTaskStackChangeListeners;

	private ActivityManagerWrapper() {
		final Context context = AppGlobals.getInitialApplication();
		mPackageManager = context.getPackageManager();
		mBackgroundExecutor = BackgroundExecutor.get();
		mTaskStackChangeListeners = new TaskStackChangeListeners(Looper.getMainLooper());
	}

	public static ActivityManagerWrapper getInstance() {
		return sInstance;
	}

	/**
	 * @return the current user's id.
	 */
	public int getCurrentUserId() {
		UserInfo ui;
		try {
			ui = ActivityManager.getService().getCurrentUser();
			return ui != null ? ui.id : 0;
		} catch (RemoteException e) {
			throw e.rethrowFromSystemServer();
		}
	}

	/**
	 * @return the top running task (can be {@code null}).
	 */
	public ActivityManager.RunningTaskInfo getRunningTask() {
		return getRunningTask(ACTIVITY_TYPE_RECENTS /* ignoreActivityType */);
	}

	public ActivityManager.RunningTaskInfo getRunningTask(@ActivityType int ignoreActivityType) {
		// Note: The set of running tasks from the system is ordered by recency
		try {
			List<ActivityManager.RunningTaskInfo> tasks = ActivityManager.getService().getTasks(10);
			if (tasks.isEmpty()) {
				return null;
			}
			return tasks.get(0);
		} catch (RemoteException e) {
			return null;
		}
	}

	/**
	 * @return a list of the recents tasks.
	 */
	public List<RecentTaskInfo> getRecentTasks(int numTasks, int userId) {
		try {
			return ActivityManager.getService().getRecentTasks(numTasks, RECENT_IGNORE_UNAVAILABLE, userId).getList();
		} catch (RemoteException e) {
			Log.e(TAG, "Failed to get recent tasks", e);
			return new ArrayList<>();
		}
	}
	
	

	/**
	 * Registers a task stack listener with the system. This should be called on the
	 * main thread.
	 */
	public void registerTaskStackListener(TaskStackChangeListener listener) {
		synchronized (mTaskStackChangeListeners) {
			mTaskStackChangeListeners.addListener(ActivityManager.getService(), listener);
		}
	}

	/**
	 * Unregisters a task stack listener with the system. This should be called on
	 * the main thread.
	 */
	public void unregisterTaskStackListener(TaskStackChangeListener listener) {
		synchronized (mTaskStackChangeListeners) {
			mTaskStackChangeListeners.removeListener(listener);
		}
	}
	
	public void startActivityInSplitScreen(Intent intent1,boolean dockTopLeft,float ratio,Intent intent2,boolean dockTopRight,float ratio2) {
		final Context context = AppGlobals.getInitialApplication();
        Intent intent = new Intent("com.android.launcher3.action.SPLIT_SCREEN");
        intent.setComponent(ComponentName.unflattenFromString("com.android.launcher3/com.android.launcher3.SplitScreenReceiver"));
//        intent.putExtra("left","org.codeaurora.dialer/com.android.dialer.main.impl.MainActivity");
//        intent.putExtra("right","com.android.settings/.Settings");
        intent.putExtra("left",ComponentName.flattenToShortString(intent1.getComponent()));
        intent.putExtra("right",ComponentName.flattenToShortString(intent2.getComponent()));
        context.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
	}
	
	public void startGoogleVoiceAssistant() {
		final Context context = AppGlobals.getInitialApplication();
        Intent intent = new Intent("com.android.intent.ext.main.open.assist");
        intent.setPackage("com.android.systemui");
        context.sendBroadcastAsUser(intent,UserHandle.SYSTEM);
	}

}
